package tgc.edu.exam.web.controller;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.exam.custom.AjaxResult;
import tgc.edu.exam.custom.CommonController;
import tgc.edu.exam.custom.dict.entity.SystemData;
import tgc.edu.exam.custom.dict.entity.SystemDictionaries;
import tgc.edu.exam.custom.dict.service.SystemDataService;
import tgc.edu.exam.custom.dict.service.SystemDicationariesService;
import tgc.edu.exam.entity.SysRole;
import tgc.edu.exam.entity.TbCurriculum;
import tgc.edu.exam.entity.Teacher;
import tgc.edu.exam.service.SysRoleService;
import tgc.edu.exam.service.TbCurriculumService;
import tgc.edu.exam.service.TeacherService;
import tgc.edu.exam.web.form.TeacherForm;

@Controller
@RequestMapping(value="/teacher")
public class TeacherController extends CommonController<Teacher, UUID, TeacherForm> {
	@Autowired
	private TeacherService service;
	@Autowired
	private TbCurriculumService tcService;
	@Autowired
	private SysRoleService roleService;
	@Autowired
	private SystemDicationariesService dictService;
	@Autowired
	private SystemDataService dataService;
	
	
	/****
	 * 重置密码
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/reset")
	@ResponseBody
	public Object reset(String id) {
		BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
		String mgs = "密码重置失败";
		if(!StringUtils.isEmpty(id)) {
			Teacher teacher = service.findById(UUID.fromString(id));
			teacher.setPassword(encoder.encode("123456"));
			service.save(teacher);
			mgs = "密码重置完成";
		}
		return mgs;
		
	}
	
	
	@Override
	public void edit(TeacherForm form, ModelMap map) throws InstantiationException, IllegalAccessException {
		SystemDictionaries systemDictionaries = dictService.findByCode("Types_of_Teachers");
		List<SystemData> data = dataService.findBySystemDictionaries(systemDictionaries);
		SystemDictionaries systemDictionaries1 = dictService.findByCode("nation");
		List<SystemData> data1 = dataService.findBySystemDictionaries(systemDictionaries1);
		SystemDictionaries systemDictionaries2 = dictService.findByCode("political_outlook");
		List<SystemData> data2 = dataService.findBySystemDictionaries(systemDictionaries2);
		SystemDictionaries systemDictionaries3 = dictService.findByCode("education");
		List<SystemData> data3 = dataService.findBySystemDictionaries(systemDictionaries3);
		SystemDictionaries systemDictionaries4 = dictService.findByCode("Class_duties");
		List<SystemData> data4 = dataService.findBySystemDictionaries(systemDictionaries4);
		map.put("data", data);
		map.put("data1", data1);
		map.put("data2", data2);
		map.put("data3", data3);
		map.put("data4", data4);
		map.put("Teacher", tcService.findAll());
		map.put("roles",roleService.findByParentIsNull());
		super.edit(form, map);
	}

	@Override
	public Object save(TeacherForm form) {
		BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
		try {
			Teacher model=new Teacher(); 
			UUID id = form.getId();
			if(id!=null) {
				model=service.findById(id);
			}else {
				model.setPassword(encoder.encode("123456"));
				model.setUsername(form.getIdcode());
			}
			model.setUsername(form.getIdcode());
			if(StringUtils.hasText(model.getPassword())) {
				model.setPassword(encoder.encode("123456"));
			}
			if(StringUtils.hasText(model.getUsername())) {
				model.setUsername(form.getIdcode());
			}
			BeanUtils.copyProperties(form, model,"id","password");
			
			List<SysRole> roles = new ArrayList<>();
			for (String code : form.getRoleIds().split(",")) {
				roles.add(roleService.findbyCode(code));
			}
			model.setRoles(roles);
			service.save(model);
			return new AjaxResult("OK");
		}catch (Exception e) {
			return new AjaxResult(false, "数据保存失败");
		}
	}

	@Override
	public Specification<Teacher> buildSpec(TeacherForm form) {
		Specification<Teacher> specification = new Specification<Teacher>() {

			private static final long serialVersionUID = 1L;
			
			@Override
			public Predicate toPredicate(Root<Teacher> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules=new HashSet<>();
				if(StringUtils.hasText(form.getName())) {
					Predicate name = cb.like(root.get("name"), "%"+form.getName()+"%");
					rules.add(name);
				}
				if(StringUtils.hasText(form.getNation())) {
					Predicate nation = cb.like(root.get("nation"), "%"+form.getNation()+"%");
					rules.add(nation);
				}
				if(StringUtils.hasText(form.getPolitics())) {
					Predicate politics = cb.like(root.get("politics"), "%"+form.getPolitics()+"%");
					rules.add(politics);
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}

		};
		return specification;
	}
	
}
